import { IWorld } from '../../engine/ecs/common/world.interface';
import { CameraComponent } from '../../engine/ecs/components/camera.component';
import { ColliderComponent } from '../../engine/ecs/components/collider.component';
import { LocationComponent } from '../../engine/ecs/components/location.component';
import { System } from '../../engine/ecs/systems/system';
import { MathUtils } from '../../engine/utilities/math-utils';
import { BulletComponent } from '../components/bullet.component';
import { camera } from '../entities/camera.entity';

export class BulletCleanupSystem extends System {
  onUpdate(world: IWorld, dt: number) {
    const cameraLocationComponent = world.findComponentByEntity(camera, LocationComponent)!;
    const cameraComponent = world.findComponentByEntity(camera, CameraComponent)!;
    const cameraLocation = cameraLocationComponent.location;
    const cameraDimension = cameraComponent.viewDimension;

    const bulletEntities = world.findEntitiesByComponent(BulletComponent);
    for (const bulletEntity of bulletEntities) {
      const bulletLocationComponent = world.findComponentByEntity(bulletEntity, LocationComponent)!;
      const bulletColliderComponent = world.findComponentByEntity(bulletEntity, ColliderComponent)!;
      const bulletLocation = bulletLocationComponent.location;

      for (const config of bulletColliderComponent.configs) {
        const bulletDimension = config.dimension;

        if (!MathUtils.isIntersection(cameraLocation, cameraDimension, bulletLocation, bulletDimension)) {
          world.removeEntity(bulletEntity);
          break;
        }
      }
    }
  }
}
